from flask import Flask, jsonify
from flask_cors import CORS
from flask_session import Session
from applications.config import config  # 导入配置字典
from applications.extensions import init_databases
from applications.view import init_bps
# 引入 Flask-JWT-Extended
from flask_jwt_extended import JWTManager


def create_app(config_name='default'):
    app = Flask(__name__,
                static_folder='static',
                static_url_path='/static',
                template_folder='templates')

    # 根据配置名称加载配置类
    app.config.from_object(config[config_name])

    # CORS 配置
    CORS(app, supports_credentials=True)
    # Session 配置
    Session(app)

    # 初始化数据库
    init_databases(app)
    jwt = JWTManager(app)
    jwt.init_app(app)

    @jwt.expired_token_loader
    def expired_token_callback(jwt_header, jwt_payload):
        return jsonify({"code": 401, "message": "Token 已过期"}), 401

    @jwt.invalid_token_loader
    def invalid_token_callback(reason):
        return jsonify({"code": 401, "message": reason}), 401

    @jwt.unauthorized_loader
    def unauthorized_callback(reason):
        return jsonify({"code": 401, "message": reason}), 401
    # 注册蓝图
    init_bps(app)

    return app

